package cn.xiaobai.service;

import android.content.Context;

import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Logger;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.xiaobai.consts.Trigger;
import cn.xiaobai.domain.Message;
import cn.xiaobai.domain.User;
import cn.xiaobai.handler.MsgHandler;
import cn.xiaobai.utils.DBUtils;
import cn.xiaobai.utils.TaskPool;

/**
 * @Author yangdaji
 * @Date 2023/12/23
 * @PackageName cn.xiaobai.service
 * @ClassName AuthorServer
 */
public class AuthorServer {

    private static Logger log = Logger.getLogger(AuthorServer.class.getName());


    private MsgHandler msgHandler;

    private AtomicBoolean isConn = new AtomicBoolean(false);

    public AuthorServer(Context context) {
        msgHandler = new MsgHandler(context);
        checkConn();
    }

    public Message doCall(String... strings) {
        String username = strings[0];
        String password = strings[1];
        String type = strings[2];

        Message result = new Message();
        if (type.equals(Trigger.LOGIN.getType())) {
            result = login(username, password);
        } else if (type.equals(Trigger.REGIS.getType())) {
            result = regis(username, password);
        }
        onPostExecute(result);
        return result;
    }

    private void onPostExecute(Message message) {
        msgHandler.setMessage(message);
        msgHandler.sendMsg(true);
    }

    /**
     * 检查连接状态
     *
     * @return
     */
    public void checkConn() {
        TaskPool.submit(() -> {
            if (!isConn.get()) {
                if (DBUtils.getConn() != null) {
                    isConn.set(true);
                } else {
                    isConn.set(false);
                }
            }
        });
    }

    public Message login(String username, String password) {

        Message message = new Message();
        if (!isConn.get()) {
            message.setMsg("数据库初始化异常");
            return message;
        }
        if (checkAcc(username, password, HandlerType.LOGIN)) {
            message.setMsg("登录成功");
            message.setSuccess(true);
        } else {
            message.setMsg("账户/密码错误");
        }
        return message;
    }

    public Message regis(String username, String password) {
        Message message = new Message();
        if (!isConn.get()) {
            message.setMsg("数据库初始化异常");
            return message;
        }
        if (checkAcc(username, password, HandlerType.REGIS)) {

            Connection conn = null;
            try {
                conn = DBUtils.getConn();
                conn.setAutoCommit(false);
                String insertUser = "insert into user(username,password) values(?,?)";
                PreparedStatement preparedStatement = conn.prepareStatement(insertUser);
                preparedStatement.setString(1, username);
                preparedStatement.setString(2, Base64.encode(password, StandardCharsets.UTF_8));
                preparedStatement.execute();
                conn.commit();
                message.setMsg("注册成功");
                message.setSuccess(true);
                return message;
            } catch (SQLException e) {
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                }
                message.setMsg("注册失败!");
            } finally {
                DBUtils.close(conn, null);
            }
        } else {
            message.setMsg(username + " 用户已存在");
        }
        return message;
    }

    /**
     * 检查
     *
     * @param username
     * @param password
     * @return
     */
    public boolean checkAcc(String username, String password, HandlerType type) {

        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return false;
        }

        String queryName = "select username, password from user where username=?";
        Connection conn = null;
        ResultSet resultSet = null;
        try {
            conn = DBUtils.getConn();
            PreparedStatement preparedStatement = conn.prepareStatement(queryName);
            preparedStatement.setString(1, username);

            resultSet = preparedStatement.executeQuery();
            User user = null;
            while (resultSet.next()) {
                String queryUser = resultSet.getString("username");
                String queryPassword = resultSet.getString("password");
                user = new User(queryUser, queryPassword);
            }

            if (HandlerType.LOGIN.equals(type)) {
                if (user != null) {
                    // 验证密码
                    if (password.equals(Base64.decodeStr(user.getPassword(), StandardCharsets.UTF_8))) {
                        // 密码验证成功
                        return true;
                    }
                }
                log.warning("账户/密码错误!");
            } else {
                // 注册
                if (user == null) {
                    return true;
                } else {
                    log.warning(username + " 用户已注册");
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtils.close(conn, resultSet);
        }
        return false;
    }


    enum HandlerType {
        LOGIN,
        REGIS
    }


}
